const cloudbase = require("@cloudbase/node-sdk");
const dayjs = require('dayjs');
const app = cloudbase.init({
    env: cloudbase.SYMBOL_CURRENT_ENV
});

const db = app.database();
// 生成订单
exports.main = async (event, context) => {
    const collection_cart = db.collection("cart");
    const collection_order = db.collection("order");
    const collection_address = db.collection("address");
    // 查询默认地址
    const res_address = await collection_address.where({'isDefault': true}).get();
    // 查询购物车
    const res_cart = await collection_cart.aggregate().lookup({
            from: 'shoes',
            localField: 'goods_id',
            foreignField: '_id',
            as: 'shoes_info'
        })
        .end();
    const now = dayjs().valueOf();
    const date = dayjs().format('YYYYMMDDHHmmssSSS');
    // 生成待支付订单
    const res_order = await collection_order.add({'status': 0,'No':date,'goods_list':res_cart.data,'_createTime':now,'_updateTime':now,'_openid':event.openid})
    return {address: res_address.data, order_id:res_order.id, goods_list: res_cart.data};
};